package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.DetailsActivity;
import com.luoxiang.socialandroid.activity.GreetActivity;
import com.luoxiang.socialandroid.activity.TestActivity;
import com.luoxiang.socialandroid.adapter.GreetAdapter;
import com.luoxiang.socialandroid.adapter.OperationsAdapter;
import com.luoxiang.socialandroid.adapter.PopupwindowAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.BeforeCallBean;
import com.luoxiang.socialandroid.bean.CreditLog;
import com.luoxiang.socialandroid.bean.GreetBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.OpBean;
import com.luoxiang.socialandroid.bean.Operation;
import com.luoxiang.socialandroid.bean.OurinfoBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.AlertDialogGreet;
import com.luoxiang.socialandroid.utils.AlertDialogUtils;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.base.CallParam;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class OperationsFragment extends LazyLoadFragment {
    private RecyclerView rc_op;
    private String token, mUserid;
    private OperationsAdapter adapter;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private RelativeLayout rela_popup;
    private ImageView icon_totop;
    private PopupwindowAdapter adapterpopp;
    private int flag;
    private RecyclerView recyclerView;
    private TextView tv_zhaohuyu;
    private PopupWindow popupWindow;
    private int zhaohuid;
    private int page = 1;//是我们的页数
    private int mCurrentPage = -1;
    private SmartRefreshLayout smartRefreshLayout;
    private List<Operation> list = new ArrayList<>();

    @Override
    protected int setContentView() {
        return R.layout.fragment_operations;
    }

    @Override
    protected void initView() {
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        mUserid = MmkvUtil.INSTANCE.decodeString(ACCID);
        rc_op = findViewById(R.id.rc_op);
        rela_popup = findViewById(R.id.rela_popup);
        icon_totop = findViewById(R.id.icon_totop);
        tv_zhaohuyu = findViewById(R.id.tv_zhaohuyu);
        smartRefreshLayout = findViewById(R.id.smartRefresh);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rc_op.setLayoutManager(linearLayoutManager);
        adapter = new OperationsAdapter();
        rc_op.setAdapter(adapter);
        getUserOperations(token, EXTRA, page, 10);
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getUserOperations(token, EXTRA, page, 10);
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mCurrentPage = -1;
                getUserOperations(token, EXTRA, page, 10);
            }
        });
    }

    @Override
    protected void lazyLoad() {
        getHostCallContents(token, EXTRA);
        initListener();
    }

    private void initListener() {
        View view1 = LayoutInflater.from(getContext()).inflate(R.layout.popover_view, null, false);
        popupWindow = new PopupWindow(view1, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        if (popupWindow.isFocusable()) {
            flag = 1;
        }

        rela_popup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flag == 1) {
                    icon_totop.setImageResource(R.mipmap.icon_tobottom);
                    flag = 0;
                    popupWindow.dismiss();
                } else {
                    popupWindow.isShowing();
                    icon_totop.setImageResource(R.mipmap.icon_totop);
                    flag = 1;//设置PopupWindow的显示位置，这里的参数分别是，参照View，X轴的偏移量，Y轴的偏移量
                    popupWindow.showAsDropDown(rela_popup, 50, 0);
                    getHostCallContents(token, EXTRA);
                    recyclerView = popupWindow.getContentView().findViewById(R.id.rv_popup);

                }

            }
        });

        //消失监听听
        popupWindow.setOnDismissListener((PopupWindow.OnDismissListener) () -> {
            if (popupWindow != null && popupWindow.isShowing()) {
                icon_totop.setImageResource(R.mipmap.icon_totop);
                flag = 1;
            } else {
                icon_totop.setImageResource(R.mipmap.icon_tobottom);
                flag = 0;//设置PopupWindow的显示位置，这里的参数分别是，参照View，X轴的偏移量，Y轴的偏移量
            }
        });

    }

    @Override
    protected void stopLoad() {
        super.stopLoad();
        popupWindow.dismiss();
    }

    @Override
    public void onDestroyView() {
        mCurrentPage = -1;
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 招呼语置顶
     *
     * @param position
     * @param id
     */
    private void topCallContent(int position, int id) {
        getRequest();
        NetUtils2.getInstance().getApiService().topCallContent(token, EXTRA, id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr00", decryptStr);
                            Gson gson = new Gson();
                            GreetBean bean = gson.fromJson(decryptStr, GreetBean.class);
                            if (bean.getCode() != 0) {
                                ToastUtils.showShort(bean.getMsg());
                            }
                            getHostCallContents(token, EXTRA);
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取招呼语列表
     *
     * @param token
     * @param extra
     */
    private void getHostCallContents(String token, String extra) {
        LogUtils.d("当前传入的分页数据为 --> " + page);
        if (mCurrentPage == page) return;
        mCurrentPage = page;
        NetUtils2.getInstance().getApiService().getHostCallContents(token, extra, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr83595", decryptStr);
                            Gson gson = new Gson();
                            GreetBean bean = gson.fromJson(decryptStr, GreetBean.class);
                            if (bean != null) {
                                if (bean.getData() != null) {
                                    if (bean.getData().getCallContents() != null) {
                                        if (bean.getData().getCallContents().get(0).getContent() != null) {
                                            tv_zhaohuyu.setText(bean.getData().getCallContents().get(0).getContent());
                                            zhaohuid = bean.getData().getCallContents().get(0).getId();//主播招呼语id
                                        } else {
                                            tv_zhaohuyu.setText(R.string.mi_meiyouzhaohuyu);
                                        }
                                    }
                                }
                            }
                            adapterpopp = new PopupwindowAdapter(bean.getData().getCallContents());
                            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
                            recyclerView.setLayoutManager(linearLayoutManager);
                            recyclerView.setAdapter(adapterpopp);
                            adapterpopp.setOnAddClickListener(new GreetAdapter.OnAddClickListener() {
                                @Override
                                public void onItemClicks(int position, int id) {
                                    topCallContent(position, id);
                                }
                            });
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        getRequest();

    }

    private void getUserOperations(String token, String extra, int page, int limit) {
        getRequest();
        NetUtils2.getInstance().getApiService().getUserOperations(token, extra, page, limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStrop", decryptStr);
                            Gson gson = new Gson();
                            OpBean bean = gson.fromJson(decryptStr, OpBean.class);


                            if (bean != null) {
                                if (bean.getData() != null) {
                                    if (bean.getData().getOperations() != null && bean.getData().getOperations().size() != 0) {

                                        adapter.setOnAddClickListener(new OperationsAdapter.OnAddClickListener() {
                                            @Override
                                            public void onItemClicks(int userid) {
                                                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                                intent.putExtra("userid", userid);
                                                startActivity(intent);
                                            }
                                        });
                                        adapter.setOnAddClickListenerDs(new OperationsAdapter.OnAddClickListenerDs() {
                                            @Override
                                            public void onItemClicksDs(int position, int userid, int id) {
                                                callUser(EXTRA, token, id, zhaohuid);
                                            }
                                        });
                                        adapter.setOnAddClickListenerSx(new OperationsAdapter.OnAddClickListenerSx() {
                                            @Override
                                            public void onItemClicksSx(int userid) {
                                                if (mUserid.equals(String.valueOf(userid))) {
                                                    ToastUtils.showShort(R.string.mi_bunenghezijiliaotian);
                                                } else {
                                                    XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(RouterConstant.CHAT_KRY, new UserInfo(userid + "", "aaa", "")).withContext(getActivity()).navigate();
                                                }
                                            }
                                        });
                                        adapter.setOnAddClickListenerSp(userid -> {
                                            //点击视频
                                            //点击视频
                                            getimPre(EXTRA, userid + "", token);
                                        });
                                    }
                                }
                                if (list != null) {
                                    if (page == 1) {
                                        list.clear();
                                    }
                                }


                                if (bean.getData() != null && bean.getData().getOperations() != null && bean.getData().getOperations().size() > 0) {
                                    if (list != null) {
                                        list.addAll(bean.getData().getOperations());
                                    }
                                    adapter.setData(list);
                                    adapter.notifyDataSetChanged();
                                } else {
                                    ToastUtils.showShort(R.string.mi_wugengduoshuju);
                                }
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }
                });
    }

    private void getimPre(String extra, String toUserId, String token) {
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        OurinfoBean bean = gson.fromJson(decryptStr, OurinfoBean.class);
                        TestActivity.ourinfoBean = bean;
                        if (bean.getCode() == 0) {
                            //可以发起通话
                            int accId = com.luoxiang.lib_common.utils.MmkvUtil.INSTANCE.decodeInt(ACCID);
                            String id = UUID.randomUUID().toString().replace("-", "");
                            CallParam param = CallParam.createSingleCallParam(2, accId + "", toUserId + "", null, null, id);
                            CallKitUI.startSingleCall(getContext(), param);
                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void callUser(String extra, String token, int operationLogId, int contentId) {
        NetUtils.getInstance().getApiService().callUser(extra, token, operationLogId, contentId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            LogUtils.i("decryptStrzhaohu", decryptStr);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void sayhello(String token, String extra, int userid) {
        NetUtils2.getInstance().getApiService().sayHello(token, extra, userid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        ToastUtils.showShort(R.string.mi_dazhaohuchenggong);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}
